package com.heima.gateway.filter;

import com.heima.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Slf4j
@Order(-1)
@Component
public class AuthorizerFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取request和response对象
        ServerHttpRequest request = exchange.getRequest();

        //获取请求接口地址
        String url = exchange.getRequest().getURI().getPath();
        log.info("拦截请求接口={}",url);

        //判断是否为登录请求
        if (url.contains("login/login_auth")) {
            //直接放行
            return chain.filter(exchange);
        }

        //获取请求头token信息
        String token = exchange.getRequest().getHeaders().getFirst("token");

        ServerHttpResponse response = exchange.getResponse();

        //判断是否有token信息
        if (token == null) {
            //设置响应401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //直接响应这次请求
            return response.setComplete();
        }

        //判断token是否有效
        Claims claims = AppJwtUtil.getClaimsBody(token);
        if (claims == null) {
            //设置响应401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //直接响应这次请求
            return response.setComplete();
        }

        //判断token是否到期
        //-1：有效，0：有效，1：过期，2：过期
        int i = AppJwtUtil.verifyToken(claims);
        if (i == 1 || i == 2) {
            //设置响应401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //直接响应这次请求
            return response.setComplete();
        }

        //获得token解析后中的用户信息
        Object userId = claims.get("id");
        //在header中添加新的信息
        ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
            httpHeaders.add("userId", userId + "");
        }).build();
        //重置header
        exchange.mutate().request(serverHttpRequest).build();

        //放行
        return chain.filter(exchange);
    }
}
